package com.huiw.archives.modules.sys.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huiw.archives.common.utils.R;
import com.huiw.archives.common.utils.gson.PerfectGson;
import com.huiw.archives.common.utils.redis.RedisUtils;
import com.huiw.archives.modules.sys.entity.WisArchivesAccount;

/**
 * 登录相关
 * 
 * @author yangc
 * @email yangcheng@huiwtech.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
@RequestMapping("sys")
public class SysController extends BaseControl {
	/*
	 * redis工具类
	 */
	@Autowired
	RedisUtils redisUtils;

	/**
	 * 登录
	 */
	@RequestMapping(value = "/login")
	public R login(@RequestParam Map<String, Object> params) throws IOException {
		// 获取完美gson
		Gson gson = PerfectGson.getGson();

		Object[] keys = new Object[] { "accountAccount", "accountPwd" };
		Object[] vals = new Object[] { params.get("username"), params.get("password") };
		if (vals[0] != null && vals[1] != null) {

			// 生成token，并保存到数据库
			List<Object> list = wisArchivesAccountService.query(new WisArchivesAccount(), keys, vals);

			if (list.size() > 0) {
				// json转为带泛型的list
				WisArchivesAccount WisArchivesAccount = gson.fromJson(gson.toJson(list.get(0)),
						new TypeToken<WisArchivesAccount>() {
						}.getType());
				redisUtils.set("token_" + WisArchivesAccount.getPid(), WisArchivesAccount.getPid(), 30 * 60);
				return R.ok().put("token", WisArchivesAccount.getPid());
			}

		}
		return R.error("账号密码有误");

	}

	/**
	 * 注册
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/regist")
	public Map<String, Object> regist(@RequestParam Map<String, Object> params) throws Exception {
		if (params.get("username") != "" && params.get("password") != "") {
			WisArchivesAccount user = new WisArchivesAccount();
			user.setAccountAccount(params.get("username").toString());
			user.setAccountPwd(params.get("password").toString());
			// 生成token，并保存到数据库
			if (wisArchivesAccountService.save(user))
				return R.ok();
		}

		return R.error("注册信息有误");
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "/logout")
	public R logout(@RequestHeader("token") String token) {
		System.out.println(token);
		if (token != null)
			redisUtils.delete("token_" + token);
		return R.ok();
	}

}
